﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ft_module_parser
{
    class Resample
    {
        // oggdec.exe -o - original.ogg | oggenc2.exe -q 6 --resample 44100 -S 0 - -o resampled.ogg
        public static bool OggResample(String newPath, String filePath, System.Diagnostics.ProcessPriorityClass priority = System.Diagnostics.ProcessPriorityClass.BelowNormal, bool hide = true, int new_sample_rate=44100, int resampler_quality=0, float vorbis_quality = 6)
        {
            String timeout = "";
            if (!hide) timeout = " & timeout.exe /T 5";

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = "/C \"ext_tools\\oggdec.exe -o - \"" + filePath + "\" | ext_tools\\oggenc2.exe -q " + vorbis_quality + " --resample " + new_sample_rate + " -S " + resampler_quality + " - -o \"" + newPath + "\"" + timeout + "\"";
            process.StartInfo.CreateNoWindow = hide;
            process.StartInfo.UseShellExecute = !hide;
            process.Start();
            process.PriorityClass = priority;
            process.WaitForExit();

            /*System.Diagnostics.Process decoder = new System.Diagnostics.Process();
            decoder.StartInfo.FileName = "ext_tools\\oggdec.exe";
            decoder.StartInfo.Arguments = "-o - \"" + filePath + "\"";
            System.Diagnostics.Process encoder = new System.Diagnostics.Process();
            encoder.StartInfo.FileName = "ext_tools\\oggenc.exe";
            encoder.StartInfo.Arguments = "-q " + vorbis_quality + "--resample " + new_sample_rate + " - S " + resampler_quality + " - -o \"" + newPath + "\"";

            decoder.StartInfo.UseShellExecute = false;
            encoder.StartInfo.UseShellExecute = false;

            decoder.StartInfo.RedirectStandardOutput = true;
            encoder.StartInfo.RedirectStandardInput = true;

            decoder.Start();
            decoder.PriorityClass = priority;

            while (decoder.StandardOutput.EndOfStream); // sleep until some data is ready
            encoder.StandardInput.Write(decoder.StandardOutput.ReadToEnd());

            encoder.Start();
            encoder.PriorityClass = priority;

            while (!decoder.HasExited)
                encoder.StandardInput.Write(decoder.StandardOutput.ReadToEnd());
            if (!decoder.StandardOutput.EndOfStream)
                encoder.StandardInput.Write(decoder.StandardOutput.ReadToEnd());

            encoder.WaitForExit();*/

            return (File.Exists(filePath));
        }
    }
}
